import Vue from "vue";
import VueRouter from "vue-router";
import Reg from "@/views/Reg/Reg";
import Login from "@/views/Login/Login";
import Main from "@/views/Main/Main";
import store from "@/store";
import UserInfo from "@/views/Menus/User/UserInfo";
import Home from "@/views/Menus/Home/Home";
import UserAvatar from "@/views/Menus/User/UserAvatar";
import UserPwd from "@/views/Menus/User/UserPwd";
import Article from "@/views/Menus/Article/ArtCate";
import ArtList from "@/views/Menus/Article/ArtList";

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
// router 原型上面加方法 push
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const routes = [
  {
    path: "/reg",
    component: Reg,
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    component: Main,
    redirect: "/home",
    children: [
      {
        path: "home",
        component: Home,
      },
      {
        path: "user-info",
        component: UserInfo,
      },
      {
        path: "user-avatar",
        component: UserAvatar,
      },
      {
        path: "user-pwd",
        component: UserPwd,
      },
      {
        path: "art-cate",
        component: Article,
      },
      {
        path: "art-list",
        component: ArtList,
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 参数1.到哪里去
// 参数2.从哪里去
// 参数3.是否放行的参数
router.beforeEach((to, from, next) => {
  //   console.log(store.state.user.token);
  //   if (!store.state.user.token && to.path !== "/login" && to.path !== "/reg") {
  //   定义一个白名单，使用 includes 数组方法 检测是否含有，返回的是布尔值，如果需要新增，加在白名单里面即可
  //   includes 判断指定元素是否在数组中，只能判断基本数据类型，类似于 indexOf
  const whiteList = ["/login", "/reg"];
  //   if (!store.state.user.token && !whiteList.includes(to.path)) {
  if (!store.state.user.token && whiteList.indexOf(to.path) == -1) {
    //  给提示
    Vue.prototype.$message.error("没登录啊笨蛋");
    next("/login");
  } else {
    next();
  }
});

export default router;
